package com.xc.xcmanage.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xc.xcmanage.domain.AjaxResult;
import com.xc.xcmanage.domain.dto.LoginBody;
import com.xc.xcmanage.domain.dto.LoginUser;
import com.xc.xcmanage.domain.pojo.SysUser;
import com.xc.xcmanage.mapper.SysUserMapper;
import com.xc.xcmanage.service.SysUserService;
import com.xc.xcmanage.utils.JwtUtil;
import com.xc.xcmanage.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 *
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public AjaxResult login(LoginBody loginBody) {

        // Authentication 封装 登录的用户信息
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword());

        Authentication authenticate;
        try {
            // AuthenticationManager 用来做认证
            authenticate = authenticationManager.authenticate(token);
            // UserDetailsService
        } catch (AuthenticationException e){
            return AjaxResult.error("用户名或密码错误");
        }

        if (Objects.isNull(authenticate)){
            return AjaxResult.error("用户名或密码错误");
        }

        LoginUser loginUser= (LoginUser) authenticate.getPrincipal();

        // 生成token
        String jwt = JwtUtil.createJWT(loginUser.getSysUser().getUserId().toString());

        // 将jwt保存到redis
        redisCache.setCacheObject("login:"+loginUser.getSysUser().getUserId(),loginUser);

        return AjaxResult.success("登录成功",jwt);
    }
}




